import time
import csv
import json
import re
from os import system

from playwright.sync_api import sync_playwright


def handle_json(json):
    csvFile = open("../data/list/storeG_20230227.csv", 'a', encoding='utf-8', newline='')
    try:
        writer = csv.writer(csvFile)
        results = json['data']['list']
        # print(results)
        for i in range(0, len(results)):
            data_list = json['data']['list'][i]
            # print(data_list)
            # print(data_list['f0'])
            # print(data_list['f1'])
            # print(data_list['f2'])
            writer.writerow((data_list['f0'], data_list['f1'], data_list['f2']))
    finally:
        csvFile.close()


def on_response(response):
    # print(response)
    if '/datasearch/data/nmpadata/search' in response.url and response.status == 200:
        handle_json(response.json())


def run():
    with sync_playwright() as p:
        for browser_type in [p.firefox]:
            # 列表末尾加百度防止监听报错
            browser = browser_type.launch(headless=False)
            # proxy = {
            #    "server": "http://27.184.152.75:2324"
            #}
            # page = browser.new_page()
            context = browser.new_context()
            page = context.new_page()
            # page.on('response', on_response)
            page.goto('https://www.nmpa.gov.cn/datasearch/search-result.html')
            # time.sleep(10)
            page.locator("text=关闭").click()

            # Click [placeholder="请选择"]
            page.locator("[placeholder=\"请选择\"]").click()

            # Click text=药品经营企业 >> nth=0
            page.fill('//*[@id="home"]/main/div[1]/div[7]/div/div[2]/input', '冀0')
            page.locator("text=药品经营企业").first.click()
            # time.sleep(2)
            page.wait_for_timeout(2000)
            page.click('//*[@id="home"]/main/div[1]/div[7]/div/div[2]/div/button')
            # time.sleep(2)
            # page.wait_for_timeout(2000)
            with context.expect_page() as new_page_info:
                register_page = new_page_info.value
                #  cancel_request(route, request):
                #    route.abort()
                # register_page.route(re.compile(r"(\.png)|(\.jpg)"), cancel_request)
                register_page.wait_for_load_state()
                # print(register_page.title())
                register_page.wait_for_timeout(5000)
                register_page.locator("text=关闭").click()
                register_page.on('response', on_response)
                register_page.wait_for_timeout(2000)
                # 设置每页展示条数
                register_page.click('//*[@id="home"]/div[3]/div[3]/div/div/span[2]/div/div/input')
                register_page.locator("text=20条/页").first.click()

                # region 定位遍历的坐标
                hello = open("../data/list/storeG_index.csv", 'r', encoding='utf-8')
                # con = hello.readline()
                strLine = hello.readline().split(',')
                print(strLine)
                con = strLine[0]
                countStr = int(strLine[1])
                print(con)
                hello.close()
                # 终止检测任务
                if con == 'end':
                    system('taskkill /F /IM cmd.exe')
                list = storeList[storeList.index(con) + 0:]

                # endregion 定位遍历的坐标
                print(list)
                print(storeList)
                # 输入筛选条件
                for item in list:
                    # 终止检测任务
                    if item == 'end':
                        system('taskkill /F /IM cmd.exe')

                    register_page.fill('//*[@id="home"]/div[3]/div[1]/div[1]/div[2]/div/input', item)
                    register_page.click('//*[@id="home"]/div[3]/div[1]/div[1]/div[2]/div/div/button')
                    # time.sleep(5)
                    # pageStr = register_page.query_selector('span.el-pagination__total').text_content()
                    # pageCount = int(pageStr.split(' ', 2)[1])
                    # print(pageCount)
                    count = countStr

                    # region 跳转到指定页码
                    register_page.wait_for_timeout(3000)
                    register_page.fill('//*[@id="home"]/div[3]/div[3]/div/div/span[3]/div/input', str(count))
                    register_page.keyboard.press("Enter")
                    register_page.wait_for_timeout(10000)
                    # endregion 跳转到指定页码

                    while True:
                        # region 记录当前节点及页码
                        with open("../data/list/storeG_index.csv", 'w', encoding='utf-8') as hello:
                            hello.write(item+","+str(count))
                        print(item + "第" + str(count) + "页")
                        # endregion 记录当前节点及页码

                        register_page.wait_for_timeout(6000)  # 设置成 4 秒就不够稳定了，也许可以再等待长一点
                        register_page.wait_for_load_state('networkidle')
                        # time.sleep(5)
                        # btn = register_page.query_selector('button.btn-next')
                        flag = register_page.query_selector('button.btn-next').get_attribute('disabled')
                        count = count + 1
                        if flag is None:
                            register_page.click('button.btn-next')
                            # register_page.click('//*[@id="home"]/div[3]/div[3]/div/button[2]')
                            register_page.wait_for_load_state('networkidle')
                        else:
                            countStr = 1
                            break
            # time.sleep(2)
            page.wait_for_timeout(2000)
            browser.close()


def init():
    global storeList
    list = ['粤CB0', '粤CB1', '粤CB2', '粤CB6', '粤CB750', '粤CB751', '粤CB752', '粤CB753', '粤CB754',
            '粤CB755', '粤CB756', '粤CB757', '粤CB758', '粤CB759', '粤CB76', '粤CD', '川CA0', '川CA3', '川CA8', '川CB ',
            '川CB0', '川CB1', '川CB2', '川CB3', '川CB5', '川CB9', '川CB812', '川CB813', '川CB816', '川CB817', '川CB818',
            '川CB82', '川CB83', '川CB87']
    # '冀CA', '冀CB（', '冀CB(', '冀CB0', '冀CB1', '冀CB11', '冀CB13', '冀CB17', '冀CB2','滇CB', '辽CA',
    # '冀CB3', '冀CB5', '冀CB6', '冀CD','鲁CB532',
    #             '豫CB2', '豫CB32', '豫CB33', '豫CB34', '豫CB36', '豫CB371', '豫CB372', '豫CB370', '豫CB373', '豫CB34', '豫CB375',
    #             '豫CB376', '豫CB377', '豫CB38', '豫CB379', '豫CB39', '豫CB7', '豫CB9', '滇CA','辽CB0', '辽CB1',
    # '辽CB41', '辽CB42', '辽CB43', '黑CA', '黑CB', '湘CA73', '湘CA74', '湘CA74','湘CB', '皖CA', '皖CB-', '皖CB0', '皖CB1',
    #             '皖CB55', '皖CB56','鲁CA','鲁CB  ','鲁CB0','鲁CB1','鲁CB2','鲁CB3','鲁CB50','鲁CB51','鲁CB52','鲁CB530','鲁CB531',
    # '鲁CB533','鲁CB534',
    # '吉B', '苏B', '浙B', '冀B', '豫B', '滇B', '辽B', '黑B', '湘B', '皖B', '鲁B', '赣B', '鄂B', '甘B', '晋B', '陕B',
    #             '闽B', '黔B', '粤B', '川B', '青B', '藏B', '琼B', '新B', '桂B', '宁B', '蒙B', '藏B', '京B', '津B', '沪B',
    # '鲁CB535','鲁CB536','鲁CB537','鲁CB538','鲁CB539','鲁CB54','鲁CB59','鲁CD',
    #             '苏CA','粤CA','粤CB ',
    # '冀A'

    storeList = ['冀（N）', '冀遵', '冀唐', '冀0', '冀1', '冀3',
                 '豫R',
                 '（滇）C', '（滇）D',
                 '辽G', '辽R', '辽V',
                 '黑G', '黑哈', '黑P', '黑E', '黑　C', '黑　E',
                 '湘G', '湘（连锁）C', '湘长食', 'DA7463010', 'CB7463005',
                 '皖G', '皖R', '皖亳',
                 '鲁（菏）', '鲁R', '鲁X', 'DA5342702',
                 '苏G ', '苏行', '苏食', '苏R',
                 '浙零', '浙乙',
                 '赣南', '赣（Ⅱ）', '赣（Ⅲ）', '赣鹰', '赣洪', '赣进', '赣兴', '赣于', '赣石', '赣T'
                 '鄂Ⅲ', '鄂R', '鄂1', '鄂2', '鄂7', '鄂0C', '鄂01', '鄂02', '鄂03', '鄂04', '鄂05', '鄂06', '鄂07', '鄂08',
                 '鄂09',
                 '甘G', '甘新', '甘宕',
                 '晋同', '晋S', '晋R',
                 '陕G', '陕R', '陕S', '陕咸', 'BA91100300', 'DA9111016',
                 '吉G', '吉（）D', '吉（Ⅲ）', '吉（Ⅱ）', '吉大', '吉R', '吉（III）', '吉（II）', '吉白', '吉Ⅱ',
                 '闽R',
                 '黔G', '黔Ｂ', '黔（仁）', '黔证', '黔J', '黔：',
                 '粤G', '粤梅', '粤兴', '粤平', '粤x', '粤埔', '粤W', '粤华', '粤J',
                 '川妆', '川　C', '川R',
                 '青岛', '粤DB769',
                 '新G',
                 '经营性', '桂R', '桂HC',
                 '宁（II）', '宁（Ⅲ）', '宁（Ⅱ）',
                 '蒙G', '蒙Ｄ', '新（Ⅱ）', '奉新（Ⅱ）', '新兵', '蒙F',
                 '沪_C',
                 '渝Ⅱ', '渝Ｃ', '渝R', 'CB0290002', 'CA0280001',
                 '银审', '丰（Ⅱ）', '兵C', '景（浮）', '上高(II)', 'HB', '虔', '袁州（Ⅲ）', '兵D', '景（乐）', '上高(III)',
                 'HN', '萍湘', '兴D', '埔C', '景(珠)', '铜鼓', '萍安', '临D', '埔D', '靖安', '万（Ⅲ）', '饶万', '饶铅', '城（Ⅲ）',
                 '九开', '万（Ⅱ）', '洪(Ⅲ)', '袁州(Ⅱ)', '城（Ⅱ）', '崆C', '武（Ⅲ）', '贺审', 'SC10-', '定SJ', '梅C', '武（Ⅱ）',
                 '高安', '饶广', '卾0', '梅D', '兴C', '堆D', '萍（Ⅲ）', '丰(Ⅲ)', '平C', '修（Ⅲ）', '抚（Ⅲ）', '抚(Ⅲ）', '抚(Ⅲ)',
                 '饶德', '丰C', '萍（Ⅱ）', '修（Ⅱ）', '抚（Ⅱ）', '抚(Ⅱ）', '抚(Ⅱ)', '饶市（Ⅲ）', '丰D', '萍乡（II）', '宜（Ⅱ)',
                 '并D', '饶信', '莆A', '鄱（Ⅱ', '翼B', '饶横', '饶德', '莆C', '鄱（II）', '翼C', '饶上', '萍芦', '（菏）J', '鄱(III)',
                 '翼D', '梅区', '萍莲', '共（Ⅲ）', '乾X', '余Ⅱ', '九（Ⅲ）', '临C', '共（II）', '饶（Ⅱ）', '余C', '九（Ⅱ）', 'GDA',
                 '晥C', '饶市', '余Ⅰ', '长', '襄', '饶婺', '晥D', '饶弋', '余I', '九（III）', '上高（Ⅱ）', '洪（Ⅱ）', '余Ⅲ', '喻C',
                 '九（II）', '景浮', '湖药（Ⅱ）', '饶玉', '袁州（II）', '萍栗', '宜（Ⅲ）', '华C', '饶直', '袁州（III）', '饶余', 'MD',
                 '华D', '榕仓', '樟（Ⅲ）', '湖药（Ⅲ）', 'SC', '籍d', '瑞(II)', '樟（Ⅱ）', '瑞（Ⅲ）', 'JY', '蕉C', '瑞药（Ⅱ）', '樟(III)',
                 '瑞(Ⅱ)', '安（Ⅲ）', '蕉D', '瑞药（Ⅲ）', '樟(II)', '运S', '安（Ⅱ）', '景Ⅲ', '瑞药（II）', 'LK', '并C', '景Ⅱ', '景III',
                 '瑞药（III）', 'MA', '九浔', '景II', '景（昌）', '上高（Ⅲ）', 'CZ', 'end']


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # a= '共 9990 条'
    # print(a.split(' ',2)[1])
    init()
    run()
